﻿(function($){
	$.fn.selectbox = function(config){
		var el = config.el;
		var url = config.url;
		var suggestWidth = config.suggestWidth ? config.suggestWidth : 150;
		var title = config.title ? config.title : "请输入";
		var flag = config.flag;
		var viewEl = el + 'View';
		var flagEl = el + 'Flag';
		var selectEl = el + 'Select';
		var onSelect = function(suggestion){
			$('#' + flagEl).val(0);
			$('#' + el).val(suggestion.data);
			$('#' + selectEl).val(suggestion.data);
			$('#' + selectEl).trigger("change");
		};
		
		var onSelectFn = config.onSelect ? config.onSelect : onSelect;
		
		if($("#" + el + "wrap").length <= 0){//判断动态创建的div是否已经存在，如果不存在则创建
			$(this).wrapAll("<div id='" + el + "wrap' style='position:relative;display:inline-block;_zoom:1;*display:inline;'></div>");
			var txtHtml = "<input type='text' id='" + viewEl + "' value='" + title + "' style='position:absolute;left:2px;top:1px;*top:2px;color:#777'/>";
			var flagHtml = "<input type='hidden' id='" + flagEl + "' value='1' />";
			var valueHtml = "<input type='hidden' id='" + el + "' />";
			
			$("#" + el + "wrap").append(txtHtml);
			$("#" + el + "wrap").append(flagHtml);
			$("#" + el + "wrap").append(valueHtml);
			
			$("#" + el).css({ width:$(this).width()-13,height:$(this).height(),border:"0px solid #c4c4c4"});
			$(this).css({"vertical-align":"middle","color":"#777"});
		}
		
		$('#' + viewEl).autocomplete({
			minChars:1, 
	        onSelect: onSelectFn,
			serviceUrl: url,
			width:suggestWidth-7,
			noCache: true
		});
		
		$('#' + viewEl).keyup(function(event){
			if(event.keyCode!=13){
				$('#' + flagEl).val(1); 
			}	
		});
		
		$('#' + viewEl).focus(function(event){
			if(this.value== title) {
				this.value='';
			}
		});
		if(flag || flag == undefined){
			$('#' + viewEl).blur(function(event){
				if($('#' + flagEl).val() == '1'){
					var temp = $('#' + el).val();
					$('#' + el).val(''); 
					$('#' + viewEl).val(title); 
					$('#' + selectEl).val("");
					if(temp != ''){
						$('#' + selectEl).trigger("change");
					}
				}
			});
		}
		
		
		$(this).change(function(){
			$('#' + flagEl).val(0); 
			$('#' + el).val($(this).val()); 
			if($(this).val() == ''){
				$('#' + viewEl).val(title); 
				
			}else{
				$('#' + viewEl).val($(this).find('option:selected').text()); 
			}
		});
		
		
		//解决ie6下select浮在div上面的bug
		$("#" + el + "div").bgIframe();
	}
})(jQuery);